/**
 * Copyright (C) 2021 - 2031 O-Cubes Co., Ltd.
 */

/****************************************************************
 *  @file    pwm.c
 *  @brief   pwm driver
 *  @version v1.0
 *  @date    03. Apr. 2023
 *  @author  liuchao
 ****************************************************************/

#include <stdint.h>

#include "pwm.h"
#include "error.h"
#include "dev_timer.h"
#include "device_timer.h"

int32_t pwm_start(enum pwm id, uint32_t duty_cycle, uint32_t hz)
{
	uint8_t er_cd = E_OK;
	uint8_t timer_id = 0;
	DEV_TIMER_PTR dev_timer = NULL;
	DEV_TIMER_CFG timer_cfg;

	if (id == PWM_0) {
		timer_id = DW_TIMER_6_ID;
	} else if (id == PWM_1) {
		timer_id = DW_TIMER_7_ID;
	} else {
		return E_PAR;
	}

	if ((hz == 0) || (duty_cycle > 100)){
		return E_PAR;
	}

	dev_timer = timer_get_dev(timer_id);

	timer_cfg.mode = DEV_TIMER_MODE_PWM;
	timer_cfg.count_high = 0;
	timer_cfg.count_low = 0;
	timer_cfg.hz = hz;
	timer_cfg.duty_cycle = duty_cycle;
	timer_cfg.int_ch_handler = NULL;

	er_cd = dev_timer->timer_control(TIMER_CMD_SET_CFG, CONV2VOID(&timer_cfg));

	return er_cd;
}

int32_t pwm_stop(enum pwm id)
{
	uint8_t er_cd = E_OK;
	uint8_t timer_id = 0;
	DEV_TIMER_PTR dev_timer = NULL;
	DEV_TIMER_CFG timer_cfg;

	if (id == PWM_0) {
		timer_id = DW_TIMER_6_ID;
	} else if (id == PWM_1) {
		timer_id = DW_TIMER_7_ID;
	} else {
		return E_PAR;
	}

	dev_timer = timer_get_dev(timer_id);
	timer_cfg.mode = DEV_TIMER_MODE_CLOSE;
	timer_cfg.count_high = 0;
	timer_cfg.count_low = 0;
	timer_cfg.duty_cycle = 0;
	timer_cfg.int_ch_handler = NULL;

	er_cd = dev_timer->timer_control(TIMER_CMD_SET_CFG, CONV2VOID(&timer_cfg));

	return er_cd;
}

